package com.service.impl;

import com.mapper.ConsumptionMapper;
import com.mapper.TaocanMapper;
import com.mapper.UserMapper;
import com.pojo.Consumption;
import com.pojo.Taocan;
import com.pojo.User;
import com.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Optional;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

@Service
public class UserServiceImpl implements UserService {
    private static final Logger logger = LoggerFactory.getLogger(UserServiceImpl.class);

    @Autowired
    private UserMapper userMapper;
    @Autowired
    private ConsumptionMapper consumptionMapper;
    @Autowired
    private TaocanMapper taocanMapper;

    @Override
    public List<User> selectUserAll() {
        return userMapper.selectUserAll();
    }

    @Override
    public User login(User user) {
        return userMapper.login(user);
    }

    @Override
    public void register(User user) {
        // 插入用户基本信息
        userMapper.register(user);

        // 根据套餐ID获取套餐信息
        Taocan taocan = taocanMapper.selectByPrimaryKey(user.getTaocan());
        if (taocan != null) {
            // 更新用户的剩余量信息
            user.setRemaining_time(taocan.getTime());
            user.setRemaining_duanxin(taocan.getDuanxin());
            user.setRemaining_liuliang(taocan.getLiuliang());

            // 更新用户记录
            userMapper.updateUser(user);
        }
    }

    @Override
    public User loginByNumberAndPassword(String number, String mima) {
        return userMapper.loginByNumberAndPassword(number, mima);
    }

    @Override
    public void triggerRandomConsumption(User user) throws Exception {
        if (user == null) {
            throw new IllegalArgumentException("用户不能为空");
        }

        logger.info("为用户 {} 生成随机消费", user.getId());

        // 生成随机场景
        Random random = new Random();
        int scenarioIndex = random.nextInt(6);

        // 定义场景信息
        String[] scenarios = {
                "问候客户，谁知其如此难缠 通话 90 分钟",
                "询问妈妈身体状况 本地通话 30 分钟",
                "参与环境保护实施方案问卷调查 发送短信 5 条",
                "通知朋友手机换号，发送短信 50 条",
                "和女友微信视频聊天 使用流量 1G",
                "晚上手机在线看韩剧，不留神睡着啦！ 使用流量 2G"
        };

        String scenario = scenarios[scenarioIndex];
        logger.info("为用户 {} 生成随机消费场景: {}", user.getId(), scenario);

        // 解析消费类型
        String consumptionType = null;
        if (scenario.contains("通话")) {
            consumptionType = "通话";
        } else if (scenario.contains("短信")) {
            consumptionType = "短信";
        } else if (scenario.contains("流量")) {
            consumptionType = "上网";
        } else {
            throw new IllegalArgumentException("无法识别消费类型: " + scenario);
        }

        // 解析数量
        Matcher matcher = Pattern.compile("(\\d+(\\.\\d+)?)").matcher(scenario);
        if (!matcher.find()) {
            throw new IllegalArgumentException("无法从场景中提取数量: " + scenario);
        }

        double quantity = Double.parseDouble(matcher.group(1));

        // 处理消费逻辑
        handleConsumption(user, consumptionType, quantity, scenario);
        logger.info("用户 {} 产生 {} 消费，数量: {}, 备注: {}",
                user.getId(), consumptionType, quantity, scenario);

        // 添加日志确认消费后用户信息
        logger.info("消费后用户余额: {}, 剩余通话: {}, 剩余短信: {}, 剩余流量: {}",
                user.getHuafei(),
                user.getRemaining_time(),
                user.getRemaining_duanxin(),
                user.getRemaining_liuliang());
    }

    private void handleConsumption(User user, String consumptionType, double quantity, String remark) throws Exception {
        // 添加参数验证
        if (user == null) {
            throw new IllegalArgumentException("用户不能为空");
        }

        // 从数据库获取套餐信息
        Taocan taocan = getTaocanById(user.getTaocan());
        if (taocan == null) {
            throw new Exception("用户套餐信息不存在");
        }

        double amount = 0;
        double remaining = 0;
        logger.info("开始处理消费：类型={}, 数量={}, 用户余额={}", consumptionType, quantity, user.getHuafei());

        // 根据消费类型处理
        switch (consumptionType) {
            case "通话":
                remaining = user.getRemaining_time() != null ? user.getRemaining_time() : 0;
                logger.info("剩余通话时间: {}", remaining);
                if (quantity <= remaining) {
                    user.setRemaining_time(remaining - quantity);
                    logger.info("使用套餐内通话，剩余时间: {}", user.getRemaining_time());
                } else {
                    double excess = quantity - remaining;
                    amount = excess * 0.2; // 超出部分0.2元/分钟
                    user.setRemaining_time(0.0);
                    user.setHuafei(user.getHuafei() - amount);
                    logger.info("超出套餐通话，超出量: {}, 费用: {}, 剩余余额: {}", excess, amount, user.getHuafei());
                }
                break;

            case "短信":
                remaining = user.getRemaining_duanxin() != null ? user.getRemaining_duanxin() : 0;
                logger.info("剩余短信数量: {}", remaining);
                if (quantity <= remaining) {
                    user.setRemaining_duanxin((int) (remaining - quantity));
                    logger.info("使用套餐内短信，剩余数量: {}", user.getRemaining_duanxin());
                } else {
                    double excess = quantity - remaining;
                    amount = excess * 0.1; // 超出部分0.1元/条
                    user.setRemaining_duanxin(0);
                    user.setHuafei(user.getHuafei() - amount);
                    logger.info("超出套餐短信，超出量: {}, 费用: {}, 剩余余额: {}", excess, amount, user.getHuafei());
                }
                break;

            case "上网":
                remaining = user.getRemaining_liuliang() != null ? user.getRemaining_liuliang() : 0;
                logger.info("剩余流量: {}GB", remaining);
                if (quantity <= remaining) {
                    user.setRemaining_liuliang(remaining - quantity);
                    logger.info("使用套餐内流量，剩余流量: {}GB", user.getRemaining_liuliang());
                } else {
                    double excess = quantity - remaining;
                    amount = excess * 1024 * 0.1; // 流量按MB计费，超出部分0.1元/MB
                    user.setRemaining_liuliang(0.0);
                    user.setHuafei(user.getHuafei() - amount);
                    logger.info("超出套餐流量，超出量: {}GB, 费用: {}, 剩余余额: {}", excess, amount, user.getHuafei());
                }
                break;

            default:
                throw new IllegalArgumentException("未知消费类型: " + consumptionType);
        }

        // 检查余额是否不足
        if (user.getHuafei() != null && user.getHuafei() < 0) {
            String errorMsg = String.format("余额不足: 消费类型=%s, 数量=%.2f, 所需费用=%.2f, 当前余额=%.2f",
                    consumptionType, quantity, amount, user.getHuafei());
            logger.warn(errorMsg);
            throw new Exception("余额不足，请充值");
        }

        // 更新用户信息
        userMapper.updateUser(user);
        logger.info("用户信息更新成功: 剩余余额={}, 剩余通话={}, 剩余短信={}, 剩余流量={}",
                user.getHuafei(), user.getRemaining_time(),
                user.getRemaining_duanxin(), user.getRemaining_liuliang());

        // 记录消费信息
        Consumption consumption = new Consumption();
        consumption.setUser_id(user.getId());
        consumption.setConsumption_type(consumptionType);
        consumption.setQuantity(quantity);
        consumption.setAmount(amount);
        consumption.setRemark(remark);
        consumption.setConsumption_time(new Date());
        consumptionMapper.insertConsumption(consumption);
        logger.info("消费记录已保存: {}", consumption);
    }

    private Taocan getTaocanById(int taocanId) {
        if (taocanId <= 0) {
            return null;
        }
        return taocanMapper.selectByPrimaryKey(taocanId);
    }

    @Override
    public List<Consumption> getConsumptionRecords(int userId) {
        return consumptionMapper.getConsumptionRecords(userId);
    }

    public void initializeUserRemainingData() {
        // 获取所有用户
        List<User> users = userMapper.selectUserAll();

        for (User user : users) {
            // 获取用户套餐
            Taocan taocan = taocanMapper.selectByPrimaryKey(user.getTaocan());
            if (taocan != null) {
                // 设置余量（如果为空）
                if (user.getRemaining_time() == null) {
                    user.setRemaining_time(taocan.getTime());
                }
                if (user.getRemaining_duanxin() == null) {
                    user.setRemaining_duanxin(taocan.getDuanxin());
                }
                if (user.getRemaining_liuliang() == null) {
                    user.setRemaining_liuliang(taocan.getLiuliang());
                }

                // 更新用户
                userMapper.updateUser(user);
            }
        }
    }

    @Override
    public User getUserById(int id) {
        return userMapper.getUserById(id);
    }

    @Override
    public Optional<User> getUserByCardNumber(String cardNumber) {
        User user = userMapper.getUserByCardNumber(cardNumber);
        return Optional.ofNullable(user);
    }

    @Override
    public void updateUser(User user) {
        userMapper.updateUser(user);
    }
}